package com.ruizhong.centercontroll;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

//import com.ruizhong.centercontroll.service.AudioCaptureService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

public class SeverActivity extends AppCompatActivity {

    private String centerServerIp;
    private MediaProjectionManager mediaProjectionManager;
    private ScreenRecordService mScreenShortService;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (service instanceof ScreenRecordService.ScreenRecordBinder) {
                mScreenShortService = ((ScreenRecordService.ScreenRecordBinder) service).getService();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // no-op
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            centerServerIp = bundle.getString("centerServerIp");
        }
        EditText centerServerIpEditText = findViewById(R.id.central_control_server_ip);
        centerServerIpEditText.setText(centerServerIp);
        checkPermission();
        Intent intent = new Intent(this, ScreenRecordService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    public boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO
            }, 1);

        }
        return false;
    }
    private Intent captureIntent;

    public void startCasting(View view) {
        this.mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        captureIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, 100);
    }

    public void stopCasting(View view) {
        mScreenShortService.stopService(captureIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
//         mediaProjection--->产生录屏数据
            mScreenShortService.startRecorder(mediaProjectionManager, resultCode, data);
        }
    }



    public void shutDownServer(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String urlString = "http://" + centerServerIp + ":8094/system/api/shutdownMachine";
                try {
                    URL url = new URL(urlString);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) { // success
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String inputLine;
                        StringBuilder response = new StringBuilder();

                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();

                        // 打印结果
                        System.out.println(response.toString());
                    } else {
                        System.out.println("GET request not worked. Response Code: " + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // 将MAC地址（格式为"XX:XX:XX:XX:XX:XX"）转换为字节数组
    private static byte[] getMacBytes(String macAddress) {
        String[] hex = macAddress.split("-");
        byte[] bytes = new byte[hex.length];
        for (int i = 0; i < hex.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex[i], 16);
        }
        return bytes;
    }

    public void turnOnServer(View view) {
        EditText macCenterServer = findViewById(R.id.mac_control_server);
        String macOfCenterServer = macCenterServer.getText().toString();
        if (macOfCenterServer == null || macOfCenterServer.trim().length() <= 0) {
            System.out.println("mac地址不可为空");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                bootUpServer(macOfCenterServer, 7);
                bootUpServer(macOfCenterServer, 9);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 假设你的 ServiceConnection 变量名为 mConnection
        if (connection != null) {
            unbindService(connection);
            connection = null;
        }
    }

    private static void bootUpServer(String macOfCenterServer, Integer port) {
        String broadcastAddress = "255.255.255.255"; // 广播地址，或者你可以指定子网广播地址
        try {
            // 将MAC地址转换为字节数组，并构造WOL数据包
            byte[] macBytes = getMacBytes(macOfCenterServer);
            byte[] magicPacket = new byte[6 + 16 * macBytes.length];

            // 设置魔术包的开头6个字节为255
            for (int i = 0; i < 6; i++) {
                magicPacket[i] = (byte) 0xFF;
            }

            // 复制MAC地址16次到魔术包
            for (int i = 0; i < 16; i++) {
                System.arraycopy(macBytes, 0, magicPacket, 6 + i * macBytes.length, macBytes.length);
            }

            // 发送数据包
            DatagramSocket socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName(broadcastAddress);
            DatagramPacket packet = new DatagramPacket(magicPacket, magicPacket.length, address, port);
            socket.send(packet);
            System.out.println("Wake-on-LAN packet sent.");
            // 关闭socket
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
